package com.marquis.cloud.shiro.filter;

import com.marquis.cloud.entity.AutUser;
import com.marquis.cloud.utils.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 解决记住我功能导致的session为空的情况
 */
public class RememberMeFilter extends FormAuthenticationFilter {

    /**
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = getSubject(request, response);
        Session session = subject.getSession();
        if(session.getAttribute(Const.SESSION_USER) == null){
            Object principal = subject.getPrincipal();
            //不为空再去获取用户信息
            if(!StringUtils.isEmpty(principal)){
                //根据用户名查询用户信息
                PropertiesUtil pu = new PropertiesUtil();
                //请求地址
                String url = pu.getZuulUrl() + "/aut/user/findByUserName";
                Map<String,Object> param = new HashMap<>();
                param.put("userName", principal);
                String data = HttpInvoker.getInstance().invoke(url, param, true);
                AutUser autUser = JSONUtil.jsonToBean(data, AutUser.class);
                //保存用户信息到session中
                session.setAttribute(Const.SESSION_USER, autUser);
            }
        }
        return true;
    }
}
